package com.lwx.suanfa.rsa;

import java.security.Key;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;
    
public class RsaUtil {
    
    private static final String algorithm = "RSA";
    private static final String transformation = "RSA/ECB/PKCS1Padding";
    
    public static final String privateKeyStr = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMsrTPIOc0quk8yxyuHUH9cqqcXl2KADxpRqvB5PNRBany8gcQ+yyYiqHiFb0V2MvApzL6Igh5n6uHxtT9/XIPd/jCRCDHbWIohrMygipxghDngijZqK1Jl0YxCLPE6lopre/kq6PHlsjNHRBqbSlRI9XQ31v2CTzwyGOXcqL9wlAgMBAAECgYBDSkIf4Z1Z3Nxi7Xfut90b3KuCOhA3X0jEG13XBBDlK76RU0NfGa4aL43vKoP7YgNdyqy6G+ANpba4r1PHJW9rMlkM+qyewR6OjJRmeEqI0vDO7hZoxdDt+lABDGifI7/ESYiLvq69kKVseexxssPzqkutD5E91EKSlnX70tBBQQJBAPMNeUQDBqaI5I/DkpDMgYjVK+6iNXRvvTn3DTLPDmxHTrNyoS4dQLLL4X6Y/Jq9dHq4Bw9NGac/JoYfL0YuHG0CQQDV/e7PmNAA1VhWuAi3y4anxcn8nRKfEOnG0U6oKG0zr1E/8HZMwk5ExPWE30TYsU3phnz3fzXaLq64vgxwivuZAkEA13XdR1ZrYdw+ydc0qZoxRoy66kvvmS2pEKaak60L+x7nfJqkmc2i2h1045ZZcA99H4Dd+Ul+8U1BKGqirNMZrQJAFVnn2QjLQDoJPWXRYN1KyzSd6bmWYQ6j9LVvnrGh67VDaxjIBPKiMpRgVuicCu7t8i38DAnCSsm7ny0/On9ziQJBAI+enDvNVmquGlVutiWq2824LeSQsAo2WZlNXTss7UAjHGk5b6OokwlWM/0plBiAV8JXXi8EmRvPHnZ7bAhQbdA=";
    public static final String publicKeyStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLK0zyDnNKrpPMscrh1B/XKqnF5digA8aUarweTzUQWp8vIHEPssmIqh4hW9FdjLwKcy+iIIeZ+rh8bU/f1yD3f4wkQgx21iKIazMoIqcYIQ54Io2aitSZdGMQizxOpaKa3v5Kujx5bIzR0Qam0pUSPV0N9b9gk88Mhjl3Ki/cJQIDAQAB";
    
    /**
     * 服务器端用的私钥，用于解密登录信息
     */
    public static final PrivateKey privateKey = RsaUtil.getPrivateKey(privateKeyStr);
    
    /**
     * 默认的加密公钥，服务器端存储了相应的私钥
     */
    public static final PublicKey publicKey = RsaUtil.getPublicKey(publicKeyStr);
    
    /**
     * 得到公钥 
     * @param key 密钥字符串（经过base64编码） 
     * @throws Exception 
     */
    public static PublicKey getPublicKey(String key) {
        try{
            byte[] keyBytes;
            keyBytes = Base64Util.decode(key);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
            PublicKey publicKey = keyFactory.generatePublic(keySpec);
            return publicKey;
        } catch(Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /** 
     * 得到私钥 
     * @param key 密钥字符串（经过base64编码） 
     * @throws Exception 
     */  
    public static PrivateKey getPrivateKey(String key)  {
        try{
            byte[] keyBytes;
            keyBytes = Base64Util.decode(key);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
            PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
            return privateKey;  
        } catch(Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 用一个密钥进行加密
     * @param key
     * @param plainText
     * @return
     * @throws Exception
     */
    public static byte[] encrypt(Key key, byte[] plainText) throws Exception {
        Cipher cipher = Cipher.getInstance(transformation);
        cipher.init(Cipher.ENCRYPT_MODE, key);  
        return cipher.doFinal(plainText);
    }
    
    /**
     * 用另外一个密钥进行解密
     * @param key
     * @param ciphertext
     * @return
     * @throws Exception
     */
    public static byte[] decrypt(Key key, byte[] ciphertext) throws Exception {
        Cipher cipher = Cipher.getInstance(transformation);
        cipher.init(Cipher.DECRYPT_MODE, key);  
        return cipher.doFinal(ciphertext);
    }

}